import sys
import json
import socket
import urllib, json, urllib2, hashlib,struct,sha,time
import smtplib  
from email.mime.text import MIMEText  
from email.header import Header  
import time
import common as bbc


if __name__ == '__main__':
    socket.setdefaulttimeout(60)
    sendTimestamp = 0
    initMoney = 5000
    rnd = 1
    while True:
        try:
            diff = bbc.getDifferenceRateBHKraken()
        except BaseException:
            print "Network Error"
        else:
            if abs(diff['xrp']['rate'] - diff['eth']['rate']) >= 0.02:
		print "------------round: " + str(rnd) + "--------------"
		rnd = rnd +1
                print time.asctime( time.localtime(time.time())) + " Price rate satisfied, Start by XRP from zb"
                nxrp_zb = initMoney / diff['xrp']['zb']
                print time.asctime( time.localtime(time.time())) + " Buy xrp: " + str(nxrp_zb)+" Cost "+ str(initMoney)
                print time.asctime( time.localtime(time.time())) + " Start transferring xrp to Kraken"
                time.sleep(60*5)

		diff = bbc.getDifferenceRateBHKraken()
                xrp2money = nxrp_zb * diff['xrp']['kr']
                print time.asctime( time.localtime(time.time()) ) + "Sell xrp from Kraken, get RMB: " + str(xrp2money)

                neth_kr = xrp2money / diff['eth']['kr']
                print time.asctime(time.localtime(time.time())) + " Buy eth from Kraken, get ETH: " + str(neth_kr)
                print time.asctime(time.localtime(time.time())) + " Start transferring eth to ZB"
                time.sleep(60*10)

		diff = bbc.getDifferenceRateBHKraken()
                neth_zb = neth_kr - 0.005
                print time.asctime(time.localtime(time.time())) + " Transfer finished, get ETH: " + str(neth_zb)
                eth2money = neth_zb * diff['eth']['zb']
                print time.asctime(time.localtime(time.time())) + " Sell eth in ZB, get RMB: " + str(eth2money)

                initMoney = eth2money

            else:
		print time.asctime( time.localtime(time.time()) )+"---Current rate is:" + str(abs(diff['xrp']['rate'] -diff['eth']['rate']))
                print "not right time to buy"
        time.sleep(10)

    
